package com.jm.dao;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.ObjectUtils.Null;
import org.apache.jasper.tagplugins.jstl.core.Set;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.jm.entity.Agenttype;
import com.jm.entity.User;
import com.jm.entity.Useraddress;
import com.jm.entity.Userstock;
import com.opensymphony.xwork2.interceptor.annotations.After;
import com.opensymphony.xwork2.interceptor.annotations.Before;
import com.sun.org.apache.bcel.internal.classfile.Code;

public class LoginDao {
//	private SessionFactory sessionFactory;
//    private Session session;
	
	public com.jm.viewmodel.User getUser(long id) throws NoSuchAlgorithmException, UnsupportedEncodingException{

		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
		Session mSession = mSessionFactory.openSession();
//		//创建服务注册对象
//        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
//        //创建会话工厂对象
//        SessionFactory mSessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
//        //会话对象
//        Session mSession = mSessionFactory.openSession();
		try {
			String hql = "select u from com.jm.entity.User u where userid=:userid";
            @SuppressWarnings("unchecked")
			List<User>users = mSession.createQuery(hql).setParameter("userid", id).list();
            if(users!=null && users.size()>0){
            	User u = users.get(0);
            	if (u!=null){
                	com.jm.viewmodel.User viewModel = new com.jm.viewmodel.User();
                	if (u.getAgenttype() != null){ 
    					viewModel.setAgenttypeid(u.getAgenttype().getTypeid());
    					viewModel.setAgenttypename(u.getAgenttype().getTypename());
    				}
                	if(u.getArea()!=null){
                		viewModel.setArea(u.getArea().getAreaname());
                		viewModel.setAreaid(Integer.valueOf(u.getArea().getAreaid()));
                	}
    				viewModel.setWechat(u.getWechat());
    				viewModel.setAuthoriSTime(u.getAuthorizestart());
    				viewModel.setAuthoriETime(u.getAuthorizeend());
    				viewModel.setAuthorizedpersonid(u.getAuthorizedpersonid());				
    				viewModel.setHeadicon(u.getHeadicon());
    				viewModel.setUserid(u.getUserid());
    				viewModel.setNickname(u.getName());
    				viewModel.setPhone(u.getPhone());
    				
    				viewModel.setmkey(Utils.EncoderByMd5(u.getUserid().toString()));
    				viewModel.setRet("0");
    				User up = (User) mSession.createQuery("select u from com.jm.entity.User u where userid=:userid").setParameter("userid", u.getAuthorizedpersonid()).list().get(0);
    				viewModel.setUpname(up.getName());

    				return viewModel;
                }
            }
            
            
            return null;
        } catch (RuntimeException e) {
            throw e;
        } finally {
			mSession.close();
//			mSessionFactory.close();
		}
	}
	
	public boolean modifyPassWord(String password,long uid){
		boolean result = false;
		//创建服务注册对象
		SessionFactory sessionFactory = SessionFactoryManager.getInstance();
        //会话对象
        Session session = sessionFactory.openSession();

        Transaction tx = session.beginTransaction();
		try {
			
	        @SuppressWarnings("unchecked")
			List<User>users = session.createQuery("from com.jm.entity.User u where u.userid=:uid").setParameter("uid", uid).list();
	        if (users!=null && users.size()>0) {
				User user = users.get(0);
				user.setPassword(password);
				session.saveOrUpdate(user);
				result = true;
			}
	        session.flush();
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			tx.commit();
			session.close();
//			sessionFactory.close();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public com.jm.viewmodel.User checkUser(String username,String password)
	{
      /*ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
      //创建会话工厂对象
      SessionFactory mSessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
      //会话对象
      Session mSession = mSessionFactory.openSession();*/
		//创建服务注册对象
				SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
		        //会话对象
		        Session mSession = mSessionFactory.openSession();
		 try { 
		       
			    List<User> user = mSession.createQuery("select u  from com.jm.entity.User u where account=:username and password=:pwd and isauthorize=1").
			    		setParameter("username", username).setParameter("pwd", password).list();	
//			    String userStr = com.alibaba.fastjson.JSON.toJSONString(user);
//			    System.out.println(userStr);
			    com.jm.viewmodel.User viewModel = new com.jm.viewmodel.User();
			    System.out.println(user.size());
				if (user.size()>0) 
				{ 	
					for(User u : user)
					{
						//new com.jm.entity.User(u.wechat,u.authorizedpersonid,u.lifepic,u.identifyicon,u.userid,
						//u.agenttype,u.authorizestart,u.authorizeend,u.phone,u.headicon,u.name)
						if (u.getAgenttype() != null){ 
							viewModel.setAgenttypeid(u.getAgenttype().getTypeid());
							viewModel.setAgenttypename(u.getAgenttype().getTypename());
						}
						if(u.getArea()!=null){
		            		viewModel.setArea(u.getArea().getAreaname());
		            		viewModel.setAreaid(u.getArea().getAreaid());
		            	}				
//						viewModel.setWechat(u.getWechat());
						viewModel.setAuthoriSTime(u.getAuthorizestart());
						viewModel.setAuthoriETime(u.getAuthorizeend());
//						viewModel.setAuthorizedpersonid(u.getAuthorizedpersonid());
//						viewModel.setHeadicon(u.getHeadicon());
						viewModel.setUserid(u.getUserid());
						viewModel.setNickname(u.getName());
//						viewModel.setPhone(u.getPhone());
						viewModel.setIsAuthorit(String.valueOf(u.getIsauthorize()));
						
						viewModel.setmkey(Utils.EncoderByMd5(u.getUserid().toString()));
						viewModel.setRet("0");
						return viewModel;
					}	
				}else{
					viewModel.setRet("1");
					return viewModel;
				}
		        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			mSession.close();
//			mSessionFactory.close();
		}
		 return null;
	}
	

}
